package com.yinhe.music.yhmusic.dialog;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.BaseActivity;

/**
 * 创建歌单弹窗
 */
public class EditDialog {


    private final static String MAX_LENGTH = "40";
    private EditDialogListener mListener;
    private Context mContext;
    private AlertDialog.Builder builder;

    public interface EditDialogListener {
        void editDialogDidConfirm(String name);
    }

    public EditDialog(@NonNull Context context, EditDialogListener listener) {
        mListener = listener;
        mContext = context;
        init();
    }

    public void show() {
        if (builder != null) {
            builder.show();
        }
    }

    public  void init() {
        builder = new AlertDialog.Builder(mContext);
        View view = View.inflate(mContext, R.layout.dialog_edit_layout, null);
        final EditText editText =  view.findViewById(R.id.editText);
        final TextView textView =  view.findViewById(R.id.text_num);

        if (mContext!= null){
            ((BaseActivity) mContext).showSoftKeyboard(editText);
        }

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String content = editText.getText().toString();
                textView.setText(content.length() + "/" + MAX_LENGTH);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        builder.setTitle("新建歌单").setView(view);
        builder.setPositiveButton("确定", (dialogInterface, i) -> {
            String name = editText.getText().toString().trim();
            if (name.length() > 0 && mListener != null) {
                mListener.editDialogDidConfirm(name);
            }
        });
        builder.setNegativeButton("取消", null);
    }
}
